package com.hd123.rumba.gwt.widget.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.DelegatingChangeListenerCollection;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;

public class LabeledComboBox extends HorizontalPanel implements LabeledBox, EnterToTab {
  private Label label;
  private ComboBox comboBox;
  private String caption;

  public LabeledComboBox() {
    setSpacing(4);

    label = new Label();
    label.setWidth("100px");
    label.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
    add(label);
    setCellVerticalAlignment(label, HorizontalPanel.ALIGN_MIDDLE);

    comboBox = new ComboBoxE();
    add(comboBox);
    setCellVerticalAlignment(comboBox, HorizontalPanel.ALIGN_MIDDLE);
  }

  public LabeledComboBox(String caption) {
    this();
    setCaption(caption);
  }

  public Label getLabel() {
    return label;
  }

  public ComboBox getComboBox() {
    return comboBox;
  }

  public void setText(String text) {
    getComboBox().setText(text);
  }

  public String getText() {
    return getComboBox().getText();
  }

  public void setCaption(String caption) {
    getLabel().setText(caption);
    this.caption = caption;
  }

  public String getCaption() {
    return getLabel().getText();
  }

  public void setRequired(boolean required) {
    DOM.setInnerHTML(label.getElement(), label.getText() + "<font color='red'>*</font>");
  }

  public void setReadOnly(boolean b) {
    getComboBox().setReadOnly(b);
    setCaption(this.caption);
  }

  public void addItem(String text) {
    getComboBox().addItem(text);
  }

  public void addItems(String[] items) {
    for (int i = 0; items != null && i < items.length; ++i)
      getComboBox().addItem(items[i]);
  }

  public void setEditable(boolean editable) {
    getComboBox().setEditable(editable);
  }

  DelegatingChangeListenerCollection changeListeners;

  public void addChangeListener(ChangeListener listener) {
    if (changeListeners == null)
      changeListeners = new DelegatingChangeListenerCollection(this, getComboBox());
    changeListeners.add(listener);
  }

  public void removeChangeListener(ChangeListener listener) {
    if (changeListeners != null)
      changeListeners.remove(listener);
  }

  public void setBoxMaxLength(int length) {
    getComboBox().setMaxLength(length);
  }

  public void setBoxWidth(String width) {
    getComboBox().setWidth(width);
  }

  public void setCaptionWidth(String width) {
    getLabel().setWidth(width);
  }

}
